angular.module('IDB.service', [])
    //add by wzh 20160509 增加一个 IDB 的 service
    .factory('IDBService', ['$q', function ($q) {
        this.myDB  = {
            name: 'chat060405',
            version: 1,
            db: {},
            createDate: "20160530",
            lastModifed: "20160530",
            author: "wzh",
            description: "本地存储聊天信息\朋友信息等",
            empty: true,

            messagesStore: "messages",//实际会加上登录用户的 userID
            usersStore: "users",
            friendsStore: "friends",
        };

        return {
            myDB: this.myDB,
            initDB: function initDB(dbName) {
                console.log('initDB 初始化数据库 ---' + dbName);
                var deferred = $q.defer();
                var result = [];                //返回的结果

                // var request = indexedDB.open(dbName, myDB.version);
                var request = window.indexedDB.open(dbName);
                request.onerror = function (e) {
                    console.log('OPen Error!');
                    //失败的话,返回 null
                    deferred.resolve(null);
                };
                request.onsuccess = function (e) {
                    this.myDB.db = e.target.result;
                    console.log('初始化数据库 onsuccess ===');
                    console.debug(this.myDB.db);
                    //成功之后,反悔一个 transaction
                    deferred.resolve(this.myDB.db);
                };

                //数据库升级处理,首次和以后升级才会执行
                request.onupgradeneeded = function (event) {
                    console.log("数据库升级处理 >>>>>>" + event.oldVersion);
                    var db = request.result;
                    console.debug(db);

                    //简单删除旧版 colections,复杂待处理
                    if (db.objectStoreNames.contains('users')) {
                        db.deleteObjectStore('users');
                    }
                    if (db.objectStoreNames.contains('messages')) {
                        db.deleteObjectStore('messages');
                    }

                    //调用数据库实例的createObjectStore方法可以创建object store
                    //建立一个 messages colection (表)
                    var messagesStore = db.createObjectStore("messages", {
                            //不指定 keyPath: "messageID"
                            autoIncrement: true
                        }
                    );

                    //只保存有过聊天的朋友
                    var friends = db.createObjectStore("friends", {
                        keyPath: "userID"
                    });

                    // 不用保存所有用户,只保存有过聊天的朋友
                    var users = db.createObjectStore("users", {
                        keyPath: "userID"
                    });

                    //给 messages 的存储对象(ObjectStore)创建 2 个索引
                    // var messagesFromIndex = this.myDB.messages.createIndex("fromIndex", "from", {unique: false});
                    // var messagesToIndex = this.myDB.messages.createIndex("toIndex", "to", {unique: false});
                    var messagesFriendIndex = messagesStore.createIndex("friendIndex", "friend", {unique: false});
                    //多字段索引方式 var messagesFriendIndex = this.myDB.messages.createIndex("friendIndex", ['from', 'to'],{unique: false});
                };

                request.onsuccess = function (result) {
                    var db = request.result;
                    console.debug("数据库升级成功啦 >>>>>>");
                    console.debug(db);
                    //成功之后,返回一个 transaction
                    deferred.resolve(db);
                };
                request.onerror = function (e) {
                    console.debug('open 打开数据库失败!');
                    deferred.reject("upgrade error ");
                };

                return deferred.promise;

            },

            //调用indexedDB.open方法就可以创建或者打开一个indexedDB
            openDB: function openDB(name) {
                var request = window.indexedDB.open(name);

                request.onsuccess = function (e) {
                    console.debug('open 打开数据库成功>>>>>>!');
                    this.myDB.db = e.target.result;
                };
                request.onerror = function (e) {
                    console.debug('open 打开数据库失败!<<<<<<');
                    deferred.reject("open error ");
                };
            },
            //关闭数据库可以直接调用数据库对象的close方法
            closeDB: function closeDB(db) {
                this.myDB.db.close();
            },
            //删除数据库使用indexedDB对象的deleteDatabase方法
            //必须 close 之后
            deleteDB: function deleteDB(name) {
                if (this.myDB.db)
                    this.myDB.db.close();

                //如果没有指定数据库,就是当前数据库
                if (name == null) name = this.myDB.db.name;

                var request = indexedDB.deleteDatabase(name);
                request.onsuccess = function (e) {
                    this.myDB.db = null;
                    this.myDB.empty = true;
                    console.debug(name + ': 删除数据库成功>>>');
                }
                request.onerror = function (e) {
                    console.debug(name + ': 删除数据库失败<<<');
                    deferred.reject("delete error ");
                }
            },


            //存储一条 朋友记录
            updateFriends: function (key, value) {
                console.log('存储一条 朋友记录 >>>>>>---');
                var deferred = $q.defer();
                var result = false;

                var storeName = "friends";
                var transaction = this.myDB.db.transaction(storeName, 'readwrite');
                var store = transaction.objectStore(storeName);
                var request = store.put(value);
                request.onsuccess = function (e) {
                    deferred.resolve(result);
                }
                request.onerror = function (e) {
                    console.log('存储一条 朋友记录 失败!');
                    deferred.reject("save error ");
                }

                return deferred.promise;
            },

            //存储一条 message
            saveMessages: function (value) {
                console.log('存储一条 message >>>>>>---');
                console.log(this.myDB.db);
                var deferred = $q.defer();
                var result = false;

                var storeName = "messages";
                var transaction = this.myDB.db.transaction(storeName, 'readwrite');
                var store = transaction.objectStore(storeName);
                var request = store.add(value);
                //存储的结果怎么处理?待处理
                request.onsuccess = function (e) {
                    result = true;
                    deferred.resolve(result);
                }
                request.onerror = function (e) {
                    console.log('存储一条 朋友记录 失败!true;');
                    deferred.reject("save error ");
                }

                return deferred.promise;
            },
            //获取一条 message
            getMessages: function (userName) {
                console.log('获取一条 message 111 <<<<<< ---' + userName);
                var deferred = $q.defer();
                var result = [];                //返回的结果

                // 循环处理 cursor 数据
                var handleResult = function (event) {
                    var cursor = event.target.result;

                    if (cursor) {
                        result.push(cursor.value);
                        //console.log('获取一条 222 message <<<<<< x333 ---' + result.length);
                        //console.log(cursor.value);
                        cursor.continue();
                    }
                    else {
                        console.log('获取数据结果: 没有了! x.length = ' + result.length);
                        console.log(result);
                    }

                };

                var storeName = "messages";
                var transaction = this.myDB.db.transaction(storeName, 'readwrite');
                var store = transaction.objectStore(storeName);
                //var request = store.openCursor();
                //按照索引查询
                var index = store.index("friendIndex");
                var boundKeyRange = IDBKeyRange.only(userName);
                //多字段查询方式 var boundKeyRange = IDBKeyRange.only(['wzh','wzh']);

                // var request = index.openCursor(userName);//'all');//'wzh');
                var request = index.openCursor(boundKeyRange);

                request.onsuccess = handleResult;
                //实务处理完成之后,返回一个 promise 接口,数据放在 数组:result
                transaction.oncomplete = function (event) {
                    deferred.resolve(result);
                };

                return deferred.promise;
            },
            //获取所有 message
            getAll: function (key, value) {
                console.log('获取所有 message >>>>>>---');
                console.log('key');
                console.log(key);
                console.log('value');
                console.log(value);
            },
        };

    }])
